package chianghao.springboot.start.web;

import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.context.NoSuchMessageException;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.lang.Nullable;


public class I18nUtils {

    private static final ConcurrentHashMap<String, ResourceBundleMessageSource> i18nSourceMap=new ConcurrentHashMap<String, ResourceBundleMessageSource>();


    protected synchronized static void set(Map<String, ResourceBundleMessageSource> _i18nSourceMap){
        i18nSourceMap.putAll(_i18nSourceMap);
    }


    public static String getMessage(String fileName, String code, @Nullable Object[] args,  Locale locale){
        ResourceBundleMessageSource source  = i18nSourceMap.get(fileName);
        try {
        	return source.getMessage(code,args,locale);
        }catch(NoSuchMessageException e) {
        	return code;
        }
    }
    
    public static String getMessage(String fileName, String code, @Nullable Object[] args,  String localeString){
    	String[] a = localeString.split("_");
    	Locale locale  = new Locale(a[0],a[1]);
        ResourceBundleMessageSource source  = i18nSourceMap.get(fileName);
        try {
        	return source.getMessage(code,args,locale);
        }catch(NoSuchMessageException e) {
        	return code;
        }
        
    }

    public static String getMessage(String fileName, String code, @Nullable Object[] args, @Nullable String defaultMessage, Locale locale){
        ResourceBundleMessageSource source  = i18nSourceMap.get(fileName);
        try {
        	return source.getMessage(code,args,defaultMessage,locale);
        }catch(NoSuchMessageException e) {
        	return code;
        }
    }
    
   

}
